package Classic150;

import java.util.Deque;
import java.util.LinkedList;

public class 简化路径 {
    public String simplifyPath(String path) {
        /*
            String的split方法，Queue使用增强for
         */
        Deque<String> queue = new LinkedList<>();
        for (String s : path.split("/")) {
            if (s.equals("..")) {
                if (!queue.isEmpty()) queue.pollLast();
            } else if (!s.isEmpty() && !s.equals(".")) queue.offer(s);
        }
        StringBuilder res = new StringBuilder();
        for (String s : queue) res.append("/").append(s);
        return res.isEmpty() ? "/" : res.toString();

        /*
            双端队列，记住api的名称
         */
        /*Deque<String> queue = new LinkedList<>();
        int left = 0;
        while (left < path.length()) {
            if (path.charAt(left) == '/' && ++left >= 0) continue;
            int right = left;
            while (right < path.length() && path.charAt(right) != '/') right++;
            String s = path.substring(left, right);
            if (s.equals("..")) {
                if(!queue.isEmpty()) queue.pollLast();
            } else if (!s.equals(".")) queue.offer(s);
            left = right;
        }
        StringBuilder res = new StringBuilder();
        while (!queue.isEmpty()) res.append('/').append(queue.poll());
        return res.isEmpty() ? "/" : res.toString();*/
    }
}
